home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6171 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  64 lines

  1. Path: bigboote.WPI.EDU!nntp!keithbar
  2. From: keithbar@owl.WPI.EDU (Keith Barrett)
  3. Newsgroups: comp.lang.c
  4. Subject: Question on string literals and char arrays
  5. Date: 23 Feb 1996 00:22:11 GMT
  6. Organization: Worcester Polytechnic Institute, Worcester, MA 01609-2280
  7. Message-ID: <KEITHBAR.96Feb22192211@owl.WPI.EDU>
  8. NNTP-Posting-Host: owl.wpi.edu
  9.  
  10.  
  11. This may have been asked before but here it is:
  12.  
  13. Could someone explain to me in very great detail what is the
  14. difference between:
  15.  
  16. main()
  17. {
  18.   char *s;
  19.   s = "Keith";
  20.   printf("%s\n", s);
  21. }
  22.  
  23. and
  24.  
  25. main()
  26. {
  27.   char s[6];
  28.   s = "Keith";
  29.   printf("%s\n", s);
  30. }
  31.  
  32. In the compiler I use (gcc version 2.7.2) the second one will not
  33. compile and the first does and works. I understand the surface of this
  34. problem and I am a grad student in computer science so I am looking
  35. for details.
  36.  
  37. I realize the s in the second example acts as a a const char * and
  38. theirfore can't be changed. That is why
  39.  
  40. char s[6] = "Keith";
  41.  
  42. is allowed.
  43.  
  44. My questions are:
  45.  
  46. 1) where exactly is the string literal located. I realize it has
  47. global scope so I assume it is created right in the data segment.
  48.  
  49. 2) what does it evaluate to. I think is is a static const char * const
  50. (a static constant char pointer to a constant char).
  51.  
  52.    "Keith"[2] evaluates to a const char right
  53.  
  54. 3) I know that a pointer variable of type (char *) is created for the
  55. first example but what about example two. Is s a (const char *)? Some
  56. books say that s in this case is not even created. Because it is a
  57. const char pointer and can't change it is never created. The real
  58. address is just used everywhere s is rather than looking it up.
  59. Assuming a non optimizing compiler.
  60.  
  61.  
  62. Any help would be appreciated,
  63. Keith Barrett
  64.